import gz.Music;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/SqlServlet")
public class SqlServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql:///student?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT&allowPublicKeyRetrieval=true";
            String user = "root";
            String pwd = "123456";
            conn = DriverManager.getConnection(url, user, pwd);
            String sql = "select * from music";
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            List<Music> musices=new ArrayList<Music>();
            while (rs.next()){
                Music music=new Music(rs.getInt("id"),rs.getString("musicName"),rs.getString("singer"),rs.getString("hint"));
                System.out.println(music.toString());
                musices.add(music);
            }
            if (rs!=null){
                rs.close();
            }if (pstm!=null){
                pstm.close();
            }if (conn!=null){
                conn.close();
            }
            request.setAttribute("name",request.getAttribute("name"));
            request.setAttribute("music",musices);
            request.getRequestDispatcher("index.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
